import math
from random import *


def split_segments(window_time_ms, segment_count):
    """
    按照分段数为指定时间窗口分段

    :param window_time_ms: 窗口时间(ms)
    :param segment_count: 分段数
    :return: 分段集合
    """
    # 计算步长
    each_segment_ms = math.ceil(window_time_ms / segment_count)
    # 开区间值
    start = 0

    dict_res_1 = {}

    for i in range(segment_count):
        multiple = i + 1
        end = multiple * each_segment_ms
        dict_res_1[i] = [start, end]
        start = end

    # 最后一组闭区间值 需要等于窗口时间数
    if dict_res_1[len(dict_res_1) - 1][1] != window_time_ms:
        dict_res_1[len(dict_res_1) - 1][1] = window_time_ms

    return dict_res_1


def find_index(cur_ms, dict_res_arg):
    """
    使用二分查找查找当前毫秒数对应的区间段索引

    :param cur_ms:
    :param dict_res_arg:
    :return:
    """

    left = 0
    right = len(dict_res_arg) - 1

    while left <= right:
        mid = int(left + (right - left) / 2)
        cur_period = dict_res_arg[mid]
        if cur_period[0] <= cur_ms < cur_period[1]:
            return mid
        elif cur_ms < cur_period[0]:
            # 代表在left - mid之间
            right = mid
        else:
            # 代表在mid - right之间
            left = mid

    # 兜底全随
    max_int = len(dict_res_arg) - 1
    return randint(0, max_int)


'''test'''
dict_res = split_segments(60000, 40)
print(f'计算的时间段为：{dict_res}')
index = find_index(7501, dict_res)
print(f'命中的索引为：{index}')
